package com.jt.www.common.controller;

import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.remote.StatisticClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "statistic")
@Api(value = "统计分析", tags = {"Statistic-Api"}, description = "统计分析-实时数据大屏")
public class StatisticController {

    public static final Logger log = LoggerFactory.getLogger(StatisticController.class);
    private final static Integer CHANNEL_CODE = 4;//整数 2旅游 3医疗 4教育 5安保 6特设 8私保 22佛山安责 不传返回所有渠道
    @Autowired
    private StatisticClient statisticClient;

    @ApiOperation(value = "每日实时投保数据统计")
    @GetMapping(value = "/edu/hour", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> accidentHour(@RequestParam(value = "insureStartDate") String insureStartDate,
                                          @RequestParam(value = "insureEndDate") String insureEndDate) {
        Map param = new HashMap();
        param.put("insureStartDate", insureStartDate);
        param.put("insureEndDate", insureEndDate);
        Map result = statisticClient.getEduDay(param);
        List<Map> dataList = (List<Map>) result.get("data");
        List<Map> timeList = new ArrayList<>();
        timeList.addAll(dataList);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        try {
            Date start = sdf.parse(insureStartDate.substring(0, 13) + ":00:00");
            Date end = sdf.parse(insureEndDate.substring(0, 13) + ":00:00");
            while (start.getTime() <= end.getTime()) {
                boolean flag = true;
                for (Map map : dataList) {
                    if (map.containsValue(sdf.format(start))) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    Map dataMap = new HashMap();
                    dataMap.put("date", sdf.format(start));
                    dataMap.put("total_prem", 0.00);
                    dataMap.put("policy_num", 0);
                    timeList.add(dataMap);
                }
                Calendar cal = Calendar.getInstance();
                cal.setTime(start);
                cal.add(Calendar.HOUR, 1);
                start = cal.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        timeList.sort((x, y) -> ((String) x.get("date")).compareTo((String) y.get("date")));

        //昨天0-9点数据相加
        BigDecimal b1Prem = new BigDecimal("0");
        BigDecimal b1Num = new BigDecimal("0");
        String yesterday = insureStartDate.substring(0, 10);
        for (Map map : timeList) {
            if ((map.get("date")).equals(yesterday + " 00:00:00") ||
                    (map.get("date")).equals(yesterday + " 01:00:00") ||
                    (map.get("date")).equals(yesterday + " 02:00:00") ||
                    (map.get("date")).equals(yesterday + " 03:00:00") ||
                    (map.get("date")).equals(yesterday + " 04:00:00") ||
                    (map.get("date")).equals(yesterday + " 05:00:00") ||
                    (map.get("date")).equals(yesterday + " 06:00:00") ||
                    (map.get("date")).equals(yesterday + " 07:00:00") ||
                    (map.get("date")).equals(yesterday + " 08:00:00") ||
                    (map.get("date")).equals(yesterday + " 09:00:00")) {
                b1Prem = b1Prem.add(new BigDecimal(map.get("total_prem").toString()));
                b1Num = b1Num.add(new BigDecimal(((Integer) map.get("policy_num")).toString()));
            }
        }
        for (Map map : timeList) {
            if ((map.get("date")).equals(yesterday + " 09:00:00")) {
                map.put("total_prem", b1Prem);
                map.put("policy_num", b1Num);
                break;
            }
        }

        //今天0-9点数据相加
        BigDecimal b2Prem = new BigDecimal("0");
        BigDecimal b2Num = new BigDecimal("0");
        String today = insureEndDate.substring(0, 10);
        for (Map map : timeList) {
            if ((map.get("date")).equals(today + " 00:00:00") ||
                    (map.get("date")).equals(today + " 01:00:00") ||
                    (map.get("date")).equals(today + " 02:00:00") ||
                    (map.get("date")).equals(today + " 03:00:00") ||
                    (map.get("date")).equals(today + " 04:00:00") ||
                    (map.get("date")).equals(today + " 05:00:00") ||
                    (map.get("date")).equals(today + " 06:00:00") ||
                    (map.get("date")).equals(today + " 07:00:00") ||
                    (map.get("date")).equals(today + " 08:00:00") ||
                    (map.get("date")).equals(today + " 09:00:00")) {
                b2Prem = b2Prem.add(new BigDecimal(map.get("total_prem").toString()));
                b2Num = b2Num.add(new BigDecimal(((Integer) map.get("policy_num")).toString()));
            }
        }

        for (Map map : timeList) {
            if ((map.get("date")).equals(today + " 09:00:00")) {
                map.put("total_prem", b2Prem);
                map.put("policy_num", b2Num);
                break;
            }
        }

        return GenericDataResponse.okWithData(timeList);
    }

    @ApiOperation(value = "630投保数据统计")
    @GetMapping(value = "/edu/630", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> accident630(@RequestParam(value = "insureStartDate") String insureStartDate,
                                         @RequestParam(value = "insureEndDate") String insureEndDate) {
        Map param = new HashMap();
        param.put("insureStartDate", insureStartDate);
        param.put("insureEndDate", insureEndDate);
        Map result = statisticClient.getEdu630(param);
        List<Map> dataList = (List<Map>) result.get("data");
        Map returnMap = new HashMap();
        returnMap.put("total_prem", dataList.get(0).get("total_prem"));
        returnMap.put("policy_num", dataList.get(0).get("policy_num"));
        return GenericDataResponse.okWithData(returnMap);
    }

    /**
     * 以下接口暂未使用，目前大屏使用特设渠道接口
     **/

    @ApiOperation(value = "按天统计历史数据")
    @GetMapping(value = "/_bai/dayStatistic", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> dayStatistic(@RequestParam(value = "insureStartDate") String insureStartDate,
                                          @RequestParam(value = "insureEndDate") String insureEndDate) {
        Map param = new HashMap();
        param.put("insureStartDate", insureStartDate);
        param.put("insureEndDate", insureEndDate);
        param.put("channelCode", CHANNEL_CODE);
        Map result = statisticClient.dayStatistic(param);
        Map data = (Map) result.get("data");

        //今年同期 = 今年同期 + 今日数据
        Map thisDay = statisticClient.thisDayStatistic(param);
        List<Map> thisDayMaps = (List<Map>) thisDay.get("data");
        Integer thisDayPolicyNum = (Integer) thisDayMaps.get(0).get("policyNum");//今日保单数量
        BigDecimal thisDayTotalPrem = new BigDecimal(thisDayMaps.get(0).get("totalPrem").toString());//今日保费总和

        List<Map> thisyearpreiods = (List<Map>) data.get("thisyearperiod");

        if (thisyearpreiods != null && thisyearpreiods.size() > 0) {
            thisyearpreiods.forEach(map -> {
                Integer policyNum = ((Integer) map.get("policyNum")) + thisDayPolicyNum;
                BigDecimal totalPrem = new BigDecimal(map.get("totalPrem").toString()).add(thisDayTotalPrem).setScale(2, BigDecimal.ROUND_HALF_UP);
                map.put("policyNum", policyNum);
                map.put("totalPrem", totalPrem);
            });
            data.put("thisyearperiod", thisyearpreiods);
        }
        return GenericDataResponse.okWithData(data);
    }

    @ApiOperation(value = "今天实时数据")
    @GetMapping(value = "/_bai/thisDayStatistic", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> thisDayStatistic(@RequestParam(value = "insureStartDate") String insureStartDate,
                                              @RequestParam(value = "insureEndDate") String insureEndDate) {
        Map param = new HashMap();
        param.put("insureStartDate", insureStartDate);
        param.put("insureEndDate", insureEndDate);
        param.put("channelCode", CHANNEL_CODE);
        Map result = statisticClient.thisDayStatistic(param);
        return GenericDataResponse.okWithData(result.get("data"));
    }

    @ApiOperation(value = "按小时统计昨天各小时数据")
    @GetMapping(value = "/_bai/hourStatistic", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> hourStatistic(@RequestParam(value = "insureStartDate") String insureStartDate,
                                           @RequestParam(value = "insureEndDate") String insureEndDate) {
        Map param = new HashMap();
        param.put("insureStartDate", insureStartDate);
        param.put("insureEndDate", insureEndDate);
        param.put("channelCode", CHANNEL_CODE);
        Map result = statisticClient.hourStatistic(param);

        List<Map> dataList = (List<Map>) result.get("data");

        //获取前一天日期
        String today = insureEndDate.substring(0, 10);
        try {
            SimpleDateFormat sj = new SimpleDateFormat("yyyy-MM-dd");
            Date d = sj.parse(today);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(d);
            calendar.add(Calendar.DATE, -1);
            today = sj.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (dataList != null && dataList.size() > 0) {
            //0-9点数据相加
            BigDecimal b2Prem = new BigDecimal("0");
            BigDecimal b2Num = new BigDecimal("0");

            for (Map map : dataList) {
                if ((map.get("date")).equals(today + " 00:00:00") ||
                        (map.get("date")).equals(today + " 01:00:00") ||
                        (map.get("date")).equals(today + " 02:00:00") ||
                        (map.get("date")).equals(today + " 03:00:00") ||
                        (map.get("date")).equals(today + " 04:00:00") ||
                        (map.get("date")).equals(today + " 05:00:00") ||
                        (map.get("date")).equals(today + " 06:00:00") ||
                        (map.get("date")).equals(today + " 07:00:00") ||
                        (map.get("date")).equals(today + " 08:00:00") ||
                        (map.get("date")).equals(today + " 09:00:00")) {
                    b2Prem = b2Prem.add(new BigDecimal(map.get("totalPrem").toString()));
                    b2Num = b2Num.add(new BigDecimal(((Integer) map.get("policyNum")).toString()));
                }
                if ((map.get("date")).equals(today + " 09:00:00")) {
                    map.put("totalPrem", b2Prem);
                    map.put("policyNum", b2Num);
                    break;
                }
            }
        }
        return GenericDataResponse.okWithData(dataList);
    }

    @ApiOperation(value = "按小时统计今天实时数据")
    @GetMapping(value = "/_bai/thisHourStatistic", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> thisHourStatistic(@RequestParam(value = "insureStartDate") String insureStartDate,
                                               @RequestParam(value = "insureEndDate") String insureEndDate) {
        Map param = new HashMap();
        param.put("insureStartDate", insureStartDate);
        param.put("insureEndDate", insureEndDate);
        param.put("channelCode", CHANNEL_CODE);
        Map result = statisticClient.thisHourStatistic(param);

        List<Map> dataList = (List<Map>) result.get("data");

        if (dataList != null && dataList.size() > 0) {
            //0-9点数据相加
            BigDecimal b2Prem = new BigDecimal("0");
            BigDecimal b2Num = new BigDecimal("0");
            String today = insureEndDate.substring(0, 10);
            for (Map map : dataList) {
                if ((map.get("date")).equals(today + " 00:00:00") ||
                        (map.get("date")).equals(today + " 01:00:00") ||
                        (map.get("date")).equals(today + " 02:00:00") ||
                        (map.get("date")).equals(today + " 03:00:00") ||
                        (map.get("date")).equals(today + " 04:00:00") ||
                        (map.get("date")).equals(today + " 05:00:00") ||
                        (map.get("date")).equals(today + " 06:00:00") ||
                        (map.get("date")).equals(today + " 07:00:00") ||
                        (map.get("date")).equals(today + " 08:00:00") ||
                        (map.get("date")).equals(today + " 09:00:00")) {
                    b2Prem = b2Prem.add(new BigDecimal(map.get("totalPrem").toString()));
                    b2Num = b2Num.add(new BigDecimal(((Integer) map.get("policyNum")).toString()));
                }
                if ((map.get("date")).equals(today + " 09:00:00")) {
                    map.put("totalPrem", b2Prem);
                    map.put("policyNum", b2Num);
                    break;
                }
            }
        }
        return GenericDataResponse.okWithData(dataList);
    }
}